Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

245
Visualizações
How to constrain a generic type in Flow to allow compare operators like < or lessThen?

Consider the following generic function in Flow:

function lessThen<T>(a: T, b: T) {
  return a < b;
}

The intention here is to instantiate lessThen with a type that allows the < operator like number or string.

In this form Flow complains about it:

return a < b;
            ^ Cannot compare `T` [1] to `T` [2]. [invalid-compare]
References:
1: function lessThen<T>(a: T, b: T) {
                           ^ [1]
1: function lessThen<T>(a: T, b: T) {
                                 ^ [2]

So I suppose I need to constrain T in lessThen to support <. But how do I do that? I was looking to something like build-in type CanUseCompareOperators so I can write:

function lessThen<T: CanUseCompareOperators>(a: T, b: T) {
  return a < b;
}

but I cannot find any.

Although in this toy example I can drop the generics and let Flow infere the type, in the real code I need this to work for a methods in a generic class when dropping generics is not an option like in:

class Foo<Key, Value> {
  binarySearch() {
    // code that uses < and > to compare keys
  }
}

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda